package com.gk.courses;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.gk.courses.model.Course;
import com.gk.courses.model.CourseException;
import com.gk.courses.model.Student;
import com.gk.courses.service.CourseService;
import com.gk.courses.service.StudentService;

public class Courses {
	
	private static final Log logger = LogFactory.getLog(Courses.class);
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext appContext = 
			new ClassPathXmlApplicationContext(new String[] {"context.xml"});
		
		logger.info(Arrays.asList(appContext.getBeanDefinitionNames()));
		
		StudentService studentService = appContext.getBean(StudentService.class);
		CourseService courseService = appContext.getBean(CourseService.class);
		
		Student studentJKarban = new Student();
		studentJKarban.setFirstName("Jirka");
		studentJKarban.setLastName("Karban");
		studentJKarban.setEmail("jkarban@gk-software.com");
		logger.info(studentJKarban);

		Student studentLKolarik = new Student();
		studentLKolarik.setFirstName("Lubos");
		studentLKolarik.setLastName("Kolarik");
		studentLKolarik.setEmail("lkolarik@gk-software.com");
		logger.info(studentLKolarik);
		
		Course courseMA1 = new Course();
		courseMA1.setName("MA1");
		
		Course courseMA2 = new Course();
		courseMA2.setName("MA2");
		
		courseService.saveCourse(courseMA1);
		courseService.saveCourse(courseMA2);
		studentService.registerStudent(studentJKarban);
		studentService.registerStudent(studentLKolarik);
		
		courseService.registerPrerequisites(courseMA1, courseMA2); // dependency of courses
		
		studentService.registerCompletedCourse(courseMA1, studentJKarban); 
		List<Course> completedCourses = studentService.getCompletedCourses(studentJKarban);
		
		List<Course> courses = courseService.getAllCourses();
		logger.info(courses);
		for (Course course : courses) {
			try {
				if ( !completedCourses.contains(course)) {
					courseService.enrollStudentInCourse(course, studentJKarban);
					logger.info(studentJKarban.getFirstName() + " " + studentJKarban.getLastName() +
							"-> you are enrolled to course " + course.getName() + " successfully.");
				}
				courseService.enrollStudentInCourse(course, studentLKolarik);
				logger.info(studentLKolarik.getFirstName() + " " + studentLKolarik.getLastName() +
						"-> you are enrolled to course " + course.getName() + " successfully.");
				
			} catch (CourseException e) {
				logger.error(studentLKolarik.getFirstName() + " " + studentLKolarik.getLastName() +
						"-> the prerequisites are missing for course " + course.getName());
			}
		}
		
		logger.info(courseMA2.getName() + " has enrolled students: " + 
				courseService.getEnrolledStudentsInCourse(courseMA2));
	}
	
	
}
